from rest_framework import mixins
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from .models import UserLike, User
from .serializers import UserLikeSerializer
from .aliyunRealAuth import Id2MetaVerify
from .service.isAttentionStatus import calculate_is_attentions, add_is_attentions_to_serializer
from .service.pagination import Pagination


# class LikeView(ModelViewSet):
#     queryset = UserLike.objects.all()
#     serializer_class = UserLikeSerializer
#     pagination_class = LikePagination
#     # 关注列表
#     def list(self, request, *args, **kwargs):
#         # 假设当前的登录用户是ID为1
#         current_user = User.objects.get(id=1)
#         # 获取所有用户的用户名 flat=True适用于查询一个字段(多个字段用False)=>此时是queryset查询集
#         # usernames = User.objects.values_list('username', flat=True)  # 建议将queryset结果使用列表生成式表达，防止values_list()改变
#         # print([i for i in usernames])
#         print(settings.ROOT_URLCONF)
#         # 查询当前用户关注列表
#         query = self.get_queryset().filter(user=current_user)
#         queryset = self.filter_queryset(query)
#         page = self.paginate_queryset(queryset)
#         if page is not None:
#             serializer = self.get_serializer(page, many=True)
#             return Response({'code': 200, 'msg': 'success', 'data': serializer.data})
#         serializer = self.get_serializer(queryset, many=True)
#         return Response({'code': 200, 'msg': 'success', 'data': serializer.data})
#
#     def fansAndFllowers(self, request, *args, **kwargs):
#         """粉丝数和关注数"""
#         current_user_id = 1
#         """求当前用户的关注数和粉丝数"""
#         # 方法1
#         # 查询当前用户的关注数
#         following_count = UserLike.objects.filter(user=current_user_id).count()
#         # 查询当前用户的粉丝数
#         followers_count = UserLike.objects.filter(target_user=current_user_id).count()
#         print(f'当前用户的关注数为:{following_count}, 粉丝数为:{followers_count}')
#
#         # 方法2
#         # 使用 annotate 进行统计
#         # 获取当前用户的关注数和粉丝数
#         user_counts = UserLike.objects.filter(
#             Q(user=current_user_id) | Q(target_user=current_user_id)
#         ).aggregate(
#             # 统计当前用户作为关注者（即 user 字段为当前用户）的记录数量，并将结果存储在 following_count 中
#             following_count=Count('target_user', filter=Q(user=current_user_id)),
#             # 统计当前用户作为被关注者（即 target_user 字段为当前用户）的记录数量，并将结果存储在 followers_count 中
#             followers_count=Count('user', filter=Q(target_user=current_user_id))
#         )
#         print(f'user_counts: {user_counts}')
#         # 从 aggregation 结果中提取关注数和粉丝数
#         following_count = user_counts['following_count'] if user_counts['following_count'] else 0
#         followers_count = user_counts['followers_count'] if user_counts['followers_count'] else 0
#         print(f'user为{current_user_id}的关注者数量: {followers_count}')
#         print(f'user为{current_user_id}的粉丝数量: {following_count}')
#         return Response({'code': 200, 'msg': 'success', 'data': ''})
#
#     def realAuth(self, request, *args, **kwargs):
#         """实人认证"""
#         user_name = request.data.get('user_name')
#         identify_num = request.data.get('identify_num')
#         access_key_id = os.environ.get('ALICLOUD_ACCESS_KEY_ID')
#         access_key_secret = os.environ.get('ALICLOUD_ACCESS_KEY_SECRET')
#         # print(f'access_key_id: {access_key_id}, access_key_secret: {access_key_secret}')
#         res = Id2MetaVerify().main(user_name, identify_num)
#         print(f'res的结果为：\n{res}')
#         return Response({'code': 200, 'msg': '认证成功', 'data': ''})

# access_key_id = os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_ID")
# access_key_secret = os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
# print(f'access_key_id为:{access_key_id}')
# print(f'access_key_secret:{access_key_secret}')

# 关注视图
class AttentionViewSet(mixins.CreateModelMixin,
                   mixins.ListModelMixin,
                   GenericViewSet):
    queryset = UserLike.objects.all()
    serializer_class = UserLikeSerializer
    pagination_class = Pagination
    def attentionList(self, request, *args, **kwargs):
        """查询关注列表"""
        user = User.objects.get(id=1)
        queryset = self.get_queryset().filter(user=user, status=True).order_by('-created_time')
        # 关注列表传1
        is_attentions = calculate_is_attentions(queryset, user, 1)
        page = self.paginate_queryset(queryset)
        if page is not None:
            # 使用context属性给序列化器传入is_fans_list字段为False
            serializer = self.get_serializer(page, many=True, context={'is_fans_list': False})
            # 将is_attentions序列化
            add_is_attentions_to_serializer(serializer, is_attentions)
            return Response({'code': 200, 'msg': '访问成功', 'data': serializer.data})
        serializer = self.get_serializer(queryset, many=True, context={'is_fans_list': False})
        add_is_attentions_to_serializer(serializer, is_attentions)
        return Response({'code': 200, 'msg': '访问成功', 'data': serializer.data})

    def createAttent(self, request, *args, **kwargs):
        """
        关注/取消关注/互相关注
        """
        user = User.objects.get(id=1)  # 获取当前用户
        user_id = request.data.get('user_id')
        if not user_id:
            return Response({'code': 400, 'msg': '缺少目标用户ID', 'data': ''})
        try:
            target_user = User.objects.get(id=user_id)
            # 当前用户是否关注了目标用户
            existing_like_from_user = UserLike.objects.filter(user=user, target_user=target_user).first()
            # 目标用户是否关注了当前用户
            existing_like_to_user = UserLike.objects.filter(user=target_user, target_user=user).first()
            if existing_like_from_user:
                if existing_like_from_user.status:  # 当前用户已经关注目标用户
                    # 检查目标用户是否也关注了当前用户
                    if existing_like_to_user and existing_like_to_user.status:
                        # 如果已经互相关注，取消当前用户的关注
                        existing_like_from_user.status = False
                        existing_like_from_user.save()
                        msg = '取消互相关注'
                        print(5555)
                    else:
                        # 取消关注
                        existing_like_from_user.status = False
                        existing_like_from_user.save()
                        msg = '取消关注'
                        print(1111)
                else:
                    # 如果当前用户的关注状态为 False，则恢复关注状态
                    existing_like_from_user.status = True
                    existing_like_from_user.save()
                    msg = '互相关注'
                    print(2222)
            else:
                # 如果当前用户尚未关注目标用户，则创建关注记录
                UserLike.objects.create(user=user, target_user=target_user, status=True)
                # 检查目标用户是否已经关注了当前用户
                if existing_like_to_user and existing_like_to_user.status:
                    msg = '互相关注'
                    print(3333)
                else:
                    msg = '关注成功'
                    print(4444)
        except Exception as e:
            return Response({'code': 404, 'msg': str(e), 'data': ''})

        return Response({'code': 200, 'msg': msg, 'data': ''})

    def fansList(self, request, *args, **kwargs):
        """查询粉丝列表"""
        user = User.objects.get(id=1)
        queryset = self.get_queryset().filter(target_user=user, status=True).order_by('-created_time')
        # 粉丝列表传2
        is_attentions = calculate_is_attentions(queryset, user, 2)
        page = self.paginate_queryset(queryset)
        if page is not None:
            # 使用context属性给序列化器传入is_fans_list字段为False
            serializer = self.get_serializer(page, many=True, context={'is_fans_list': True})
            # 将is_attentions序列化
            add_is_attentions_to_serializer(serializer, is_attentions)
            return Response({'code': 200, 'msg': '查询成功', 'data': serializer.data})
        serializer = self.get_serializer(queryset, many=True, context={'is_fans_list': True})
        add_is_attentions_to_serializer(serializer, is_attentions)
        return Response({'code': 200, 'msg': '查询成功', 'data': serializer.data})

    def realAuth(self, request, *args, **kwargs):
        """实人认证"""
        username = request.data.get('username', None)
        identify_num = request.data.get('identify_num', None)
        if username is None or identify_num is None:
            return Response({'code': 400, 'msg': '用户名或身份证号不能为空', 'data': ''})
        res = Id2MetaVerify().main(username, identify_num)
        if int(res.body.code) == 200:
            return Response({'code': int(res.body.code), 'msg': res.body.message, 'data': ''})
        else:
            return Response({'code': int(res.body.code), 'msg': '传入的姓名或身份证号不符合规则', 'data': ''})